const ServerConfig = require('../server.config.js')

const listen = (port,app) => {
    return new Promise((resolve, reject) => {
      const server = app.listen(port)
      const duration = ServerConfig.addTick // 重试间隔
      let left = ServerConfig.addTimes // 重试次数
      let showErrMsg = true
  
      server.on('listening', () => {
        resolve(`app listening at http://localhost:${port}`)
      })
      server.on('error', (error) => {
        if (error.code !== 'EADDRINUSE') { // 系统非监听端口操作报错
          throw error
        }
  
        left = left - 1
        if (showErrMsg) {
            port+=ServerConfig.addNumber
            console.log(`port ${port} already in use`)
            showErrMsg = false
        }
        console.log(`trying to restart the service on port ${port}... attempts left ${left} `)
        if (left !== 0) {
          setTimeout(() => server.listen(port,app), duration)
        } else {
          reject('Server is shutting down')
        }
      })
    })
  }
  //自动转化端口
  module.exports = listen